package com.exception;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.errorcode.BaseErrorCode;
import com.result.Result;
import com.result.Results;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 全局异常处理器
 *
 */
@Component
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截参数验证异常
     */
    @SneakyThrows
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result validExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        FieldError firstFieldError = CollectionUtil.getFirst(bindingResult.getFieldErrors());
        String exceptionStr = Optional.ofNullable(firstFieldError)
                .map(FieldError::getDefaultMessage)
                .orElse(StrUtil.EMPTY);
        return Results.failure(BaseErrorCode.CLIENT_ERROR.code(), exceptionStr);
    }

    /**
     * 拦截应用内抛出的异常
     */
    @ExceptionHandler(value = {AbstractException.class})
    public Result abstractException(HttpServletRequest request, AbstractException ex) {
        if (ex.getCause() != null) {
            log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), ex.toString(), ex.getCause());
            return Results.failure(ex);
        }
        log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), ex.toString());
        return Results.failure(ex);
    }

    /**
     * 数据库异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler(DbException.class)
    public Object handleDbException(DbException e) {
        log.error("mysql数据库操作异常 -> ", e);
        return processResponse(e);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Object handleIllegalArgumentException(IllegalArgumentException e) {
        log.error("数据大盘异常 -> ", e);
        if(e.getMessage().equals(BaseErrorCode.DATA_ANALYSIS_RANGE60.message())){
            log.error(BaseErrorCode.DATA_ANALYSIS_RANGE60.code(),BaseErrorCode.DATA_ANALYSIS_RANGE60.message());
            return processResponse(new AbstractException(null,null,BaseErrorCode.DATA_ANALYSIS_RANGE60) {
            });
        }
        if(e.getMessage().equals(BaseErrorCode.DATA_ANALYSIS_END_BEGIN.message())){
            log.error(BaseErrorCode.DATA_ANALYSIS_END_BEGIN.code(),BaseErrorCode.DATA_ANALYSIS_END_BEGIN.message());
            return processResponse(new AbstractException(null,null,BaseErrorCode.DATA_ANALYSIS_END_BEGIN) {
            });
        }
        return Results.error(e.getMessage());

    }

    private ResponseEntity<Result<Void>> processResponse(AbstractException e){
        return ResponseEntity.status(400).body(Results.failure(e.getErrorCode(), e.getErrorMessage()));
    }
}
